<template>
  <div>
    <source-upload class="source-upload" ref="su"></source-upload>

    <div class="clear-draft" @click="clear">
      <i class="iconfont icon-clear" title="清空所有内容"></i>
    </div>
  </div>
</template>

<script>
import { sliceFile } from '@/utils/file.js'
import { assertLogin } from '@/utils/assert.js'

import SourceUpload from './source/SourceUpload.vue';

  export default {
    components: {
      SourceUpload,
    },
    data() {
      return {
        draft: null
      }
    },
    computed: {
      draftId() {
        let id = parseInt(this.$route.query.draftId);
        if(isNaN(id)) id = undefined;
        return id;
      }
    },
    watch: {
      $route: {
        handler(nv, ov) {
          if(nv.path === '/publish/source'){
            assertLogin().then(flag => {
              if(flag) {
                this.fillDraft()
              } else {
                this.$open('/');
              }
            });
          }
        },
        immediate: true
      }
    },
    methods: {
      pubSource(sourceInfos) {
        let chunkSize = this.$chunkSize;
        let payload = {
          ...sourceInfos,
          is_charged: 0,
        }
        let file = sourceInfos.file;
        let chunkNum = Math.ceil(file.size / chunkSize);
        if(file.size > chunkSize) {
          let promise = this.$post({
            name: 'upload source init',
            url: 'source/content/submit',
            data: {
              ...payload,
              file: this.$file.sliceFile(file, 0, chunkSize),
            }
          }).then(res => {
            if(res.data.success) {
              this.$progress(true, 1 / chunkNum);
              return res.data.object;
            } else {
              this.$progress(false, 0);
              throw new Error(res.data.message);
            }
          }).catch(error => {
            this.$progress(false, 0);
            throw new Error(error.message);
          });
          let lastPromise = promise;
          for(let i = 1; i < chunkNum; i++) {
            lastPromise = lastPromise.then(filePath => {
              return this.$post({
                name: `upload source ${i} / ${chunkNum}`,
                url: 'source/content/file/upload',
                data: {
                  page: i,
                  page_num: chunkNum,
                  chunk: this.$file.sliceFile(file, chunkSize * i, chunkSize * (i + 1)),
                  file_path: filePath
                }
              }).then(res => {
                if(res.data.success) {
                  this.$progress(true, (i + 1) / chunkNum);
                  return filePath;
                } else {
                  this.$progress(false, 0);
                  throw new Error(res.data.message);
                }
              }).catch(error => {
                this.$progress(false, 0);
                throw new Error(error.message);
              })
            })
          }
          return lastPromise.then(() => {
            this.$progress(false, 0);
            return {
              data: {
                success: true,
                message: '',
                object: null
              }
            };
          }).catch(error => {
            this.$progress(false, 0);
            throw new Error(error.message);
          });
        }
        else {
          return this.$post({
            name: 'pub source',
            url: 'source/content/submit',
            data: payload
          })
        }
      },
      storeSource(sourceInfos) {
        let payload = {
          ...sourceInfos,
          is_charged: 0,
        }
        return this.$post({
          name: 'store source',
          url: 'source/content/draft/store',
          data: payload
        })
      },
      updateSourceDraft(sourceInfos) {
        let payload = {
          ...sourceInfos,
          is_charged: 0,
        }
        return this.$post({
          name: 'update source draft',
          url: 'source/content/draft/update',
          data: payload
        })
      },
      
      fillDraft() {
        if(this.draftId === undefined) return;
        let draftId = this.draftId;
        this.$fetch({
          name: 'source draft',
          url: 'creator/source/draft',
          method: 'POST',
          data: {
            id: draftId
          }
        }).then(res => {
          if(res.data.success) {
            this.draft = res.data.object;
            this.draft.tag = this.draft.tagList.map(item => item.name);
            this.draft.type = this.draft.typeList.map(item => item.name);
            this.$refs.su.fillDraft(this.draft);
          } else {
            this.$alert({
              type: 'error',
              content: '获取草稿失败'
            })
          }
        }).catch(error => {
          this.$alert({
            type: 'error',
            content: '获取草稿失败'
          })
        })
      },

      clear() {
        this.$confirm("清空所有内容？", flag => {
          if(flag) this.$refs.su.clear();
        })
      }
    },
  }
</script>

<style lang="less" scoped>
@iw: 900px;

.source-upload {
  --sourceUploadWidth: @iw;
  margin: calc(var(--topNavHeight) + 10px) auto 0;
}

.clear-draft {
  --a: 3.5vw;
  position: fixed;
  right: 5vw;
  top: calc(3 * var(--topNavHeight));
  width: var(--a);
  height: var(--a);
  border-radius: 30%;

  &:hover {
    background-color: var(--slightBlue);
    color: var(--darkBlue);
  }

  .iconfont {
    display: block;
    width: var(--a);
    height: var(--a);
    line-height: var(--a);
    text-align: center;
    font-size: calc(var(--a) * 0.5);

    &:hover {
      cursor: pointer;
    }
  }
}
</style>